<template>
  <div class="file-list-container">
    <!-- 视图切换 -->
    <div class="view-controls">
      <el-radio-group v-model="viewMode" @change="handleViewModeChange">
        <el-radio-button label="list">
          <el-icon><List /></el-icon>
        </el-radio-button>
        <el-radio-button label="grid">
          <el-icon><Grid /></el-icon>
        </el-radio-button>
      </el-radio-group>
      
      <div class="sort-controls">
        <el-select v-model="sortField" placeholder="排序方式" @change="handleSortChange">
          <el-option label="按名称" value="name" />
          <el-option label="按大小" value="size" />
          <el-option label="按修改时间" value="time" />
        </el-select>
        <el-button 
          :icon="sortOrder === 'asc' ? SortUp : SortDown" 
          @click="toggleSortOrder"
          circle
        />
      </div>
    </div>

    <!-- 列表视图 -->
    <div v-if="viewMode === 'list'" class="list-view">
      <el-table
        :data="displayData"
        :loading="loading"
        @selection-change="handleSelectionChange"
        @row-dblclick="handleRowDoubleClick"
        @row-contextmenu="handleRowContextMenu"
        row-key="id"
        height="100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="名称" min-width="200">
          <template #default="{ row }">
            <div class="file-name">
              <el-icon class="file-icon">
                <component :is="getFileIcon(row)" />
              </el-icon>
              <span class="name-text">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="路径" min-width="200">
          <template #default="{ row }">
            <span v-if="row.folderPath" class="folder-path">{{ row.folderPath }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="大小" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.type === 'file'">{{ row.sizeFormatted }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="修改时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.updateTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button 
                size="small" 
                @click="handlePreview(row)"
                :disabled="row.type === 'folder' || !row.canPreview"
              >
                预览
              </el-button>
              <el-button 
                size="small" 
                @click="handleDownload(row)"
                :disabled="row.type === 'folder'"
              >
                下载
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 网格视图 -->
    <div v-else class="grid-view">
      <div class="grid-container">
        <div
          v-for="item in displayData"
          :key="item.id"
          class="grid-item"
          @dblclick="handleItemDoubleClick(item)"
          @contextmenu="handleItemContextMenu(item, $event)"
        >
          <div class="item-icon">
            <el-icon>
              <component :is="getFileIcon(item)" />
            </el-icon>
          </div>
          <div class="item-name" :title="item.name">
            {{ item.name }}
          </div>
          <div class="item-info">
            <span v-if="item.type === 'file'">{{ item.sizeFormatted }}</span>
            <span v-else>{{ item.fileCount || item.folderCount }} 项</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && displayData.length === 0" class="empty-state">
      <el-empty description="暂无文件" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import {
  List,
  Grid,
  SortUp,
  SortDown,
  Folder,
  FolderOpened,
  Document,
  Picture,
  VideoPlay,
  Headset,
  Files,
  Download
} from '@element-plus/icons-vue'
import type { CdFileVo, CdFolderVo } from '@/types/cd'

interface Props {
  files: CdFileVo[]
  folders: CdFolderVo[]
  loading: boolean
  currentFolderId: number | string
}

interface Emits {
  (e: 'file-select', file: CdFileVo): void
  (e: 'file-double-click', file: CdFileVo): void
  (e: 'file-context-menu', file: CdFileVo, event: MouseEvent): void
  (e: 'folder-double-click', folder: CdFolderVo): void
  (e: 'selection-change', files: CdFileVo[], folders: CdFolderVo[]): void
  (e: 'file-download', file: CdFileVo): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 视图模式
const viewMode = ref<'list' | 'grid'>('list')
const sortField = ref<'name' | 'size' | 'time'>('name')
const sortOrder = ref<'asc' | 'desc'>('asc')

// 合并显示数据
const displayData = computed(() => {
  const data = [
    ...props.folders.map(folder => ({
      ...folder,
      id: `folder-${folder.folderId}`,
      type: 'folder' as const,
      name: folder.folderName,
      sizeFormatted: folder.folderSizeFormatted,
      folderPath: folder.folderPath
    })),
    ...props.files.map(file => ({
      ...file,
      id: `file-${file.fileId}`,
      type: 'file' as const,
      name: file.originalName,
      sizeFormatted: file.fileSizeFormatted,
      folderPath: file.folderPath
    }))
  ]
  
  // 排序
  return data.sort((a, b) => {
    let comparison = 0
    
    switch (sortField.value) {
      case 'name':
        comparison = a.name.localeCompare(b.name)
        break
      case 'size':
        comparison = (a.sizeFormatted || '').localeCompare(b.sizeFormatted || '')
        break
      case 'time':
        comparison = new Date(a.updateTime).getTime() - new Date(b.updateTime).getTime()
        break
    }
    
    return sortOrder.value === 'asc' ? comparison : -comparison
  })
})

// 获取文件图标
const getFileIcon = (item: any) => {
  if (item.type === 'folder') {
    return item.expanded ? FolderOpened : Folder
  }
  
  // 根据文件类型返回不同图标
  const fileType = item.fileType || ''
  switch (fileType) {
    case 'image':
      return Picture
    case 'video':
      return VideoPlay
    case 'audio':
      return Headset
    case 'document':
      return Document
    default:
      return Files
  }
}

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 事件处理
const handleViewModeChange = () => {
  // 视图模式切换逻辑
}

const handleSortChange = () => {
  // 排序变化逻辑
}

const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
}

const handleSelectionChange = (selection: any[]) => {
  const files: CdFileVo[] = []
  const folders: CdFolderVo[] = []
  
  selection.forEach(item => {
    if (item.type === 'file') {
      files.push(item as CdFileVo)
    } else {
      folders.push(item as CdFolderVo)
    }
  })
  
  emit('selection-change', files, folders)
}

const handleRowDoubleClick = (row: any) => {
  if (row.type === 'file') {
    emit('file-double-click', row as CdFileVo)
  } else {
    emit('folder-double-click', row as CdFolderVo)
  }
}

const handleRowContextMenu = (row: any, column: any, event: MouseEvent) => {
  event.preventDefault()
  if (row.type === 'file') {
    emit('file-context-menu', row as CdFileVo, event)
  }
}

const handleItemDoubleClick = (item: any) => {
  if (item.type === 'file') {
    emit('file-double-click', item as CdFileVo)
  } else {
    emit('folder-double-click', item as CdFolderVo)
  }
}

const handleItemContextMenu = (item: any, event: MouseEvent) => {
  event.preventDefault()
  if (item.type === 'file') {
    emit('file-context-menu', item as CdFileVo, event)
  }
}

const handlePreview = (item: any) => {
  if (item.type === 'file' && item.canPreview) {
    emit('file-double-click', item as CdFileVo)
  }
}

const handleDownload = (item: any) => {
  if (item.type === 'file') {
    // 找到对应的文件并emit给父组件处理
    const file = props.files.find(f => `file-${f.fileId}` === item.id)
    if (file) {
      emit('file-download', file)
    }
  }
}
</script>

<style scoped lang="scss">
.file-list-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.view-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #e4e7ed;
  
  .sort-controls {
    display: flex;
    gap: 8px;
    align-items: center;
  }
}

.list-view {
  flex: 1;
  overflow: hidden;
  
  :deep(.el-table) {
    height: 100%;
    
    .file-name {
      display: flex;
      align-items: center;
      
      .file-icon {
        margin-right: 8px;
        color: #409eff;
      }
      
      .name-text {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    
    .folder-path {
      color: #909399;
      font-size: 12px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.grid-view {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
  padding: 0 16px;
}

.grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  .item-icon {
    font-size: 48px;
    color: #409eff;
    margin-bottom: 8px;
  }
  
  .item-name {
    font-size: 14px;
    text-align: center;
    word-break: break-all;
    margin-bottom: 4px;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .item-info {
    font-size: 12px;
    color: #909399;
    text-align: center;
  }
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
